/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.api.service.impl;

import com.chinamobile.cmss.lakehouse.api.service.BaseService;
import com.chinamobile.cmss.lakehouse.common.Constants;
import com.chinamobile.cmss.lakehouse.common.enums.Status;
import com.chinamobile.cmss.lakehouse.common.enums.UserType;
import com.chinamobile.cmss.lakehouse.common.utils.Result;
import com.chinamobile.cmss.lakehouse.dao.entity.UserEntity;

import java.text.MessageFormat;
import java.util.Map;

public class BaseServiceImpl implements BaseService {

    @Override
    public boolean isAdmin(UserEntity user) {
        return user.getUserType() == UserType.ADMIN_USER;
    }

    @Override
    public boolean isNotAdmin(UserEntity loginUser, Map<String, Object> result) {
        //only admin can operate
        if (!isAdmin(loginUser)) {
            putMessage(result, Status.USER_NO_OPERATION_PERM);
            return true;
        }
        return false;
    }

    @Override
    public void putMessage(Map<String, Object> result, Status status, Object... statusParams) {
        result.put(Constants.STATUS, status);
        if (statusParams != null && statusParams.length > 0) {
            result.put(Constants.MESSAGE, MessageFormat.format(status.getMessage(), statusParams));
        } else {
            result.put(Constants.MESSAGE, status.getMessage());
        }
    }

    @Override
    public void putMessage(Result result, Status status, Object... statusParams) {
        result.setCode(status.getCode());
        if (statusParams != null && statusParams.length > 0) {
            result.setMessage(MessageFormat.format(status.getMessage(), statusParams));
        } else {
            result.setMessage(status.getMessage());
        }
    }

    @Override
    public boolean check(Map<String, Object> result, boolean allowed, Status userNoOperationPerm) {
        // only admin can operate
        if (allowed) {
            result.put(Constants.STATUS, userNoOperationPerm);
            result.put(Constants.MESSAGE, userNoOperationPerm.getMessage());
            return true;
        }
        return false;
    }

    @Override
    public boolean isAllowed(UserEntity user, String userId) {
        return user.getUserId().equals(userId) || isAdmin(user);
    }

}
